package com.livestocksolutions.intent;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.livestocksolutions.Business;
import com.livestocksolutions.Feed;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.Location;
import com.livestocksolutions.Paddock;
import com.livestocksolutions.R;
import com.livestocksolutions.ui.ViewCattleArrayAdapter;
import com.livestocksolutions.ui.ViewFeedArrayAdapter;
import com.livestocksolutions.ui.ViewUsableItemArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

/* -- Version History --
 *  1.0 : 17 September 2012 - Initial version.
 *  
 *  2.0 : 27 Janurary 2013 - Changed structure of underlying classes resulting
 *                   in an update of how the data for the particular objects are
 *                   handled.
 */

/**
 * A class to create the layout for a Feed object
 * @author Adam Parr
 * @version 2.0
 * 
 * @.modified 27 January 2013
 */
public class FeedActivity extends BaseActivity {
	public static final int FEEDVIEW 	 = 0;
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #FEEDVIEW
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.item,
	};
	
	/**
	 * The id of the Location Object
	 */
	protected long location = 0;
	/**
	 * the id of the Owner Object
	 */
	protected long owner = 0;
	
	/**
	 * Data related to this Joining.
	 */
	protected ViewFeedArrayAdapter feedView;
	
	/**
	 * Constructor
	 */
	public FeedActivity() {
		super(RESOURCEID);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(stack.size()==0){
        	setContentView(RESOURCEID[FEEDVIEW]);
        	if(!built){
	    		// Read initial state of the Feed Object
    			id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
    			Feed f = (Feed)LivestockSolutions.getUsableItemByID(id);
    			
    			// Read initial state of the Join Object
	            String[] feedType = new String[ViewFeedArrayAdapter.SIZE];
	            feedType[ViewUsableItemArrayAdapter.ID] 			= String.valueOf(f.getID());
//	            feedType[ViewFeedArrayAdapter.CVDNO]				= f.getCVDNumber();
//	            feedType[ViewUsableItemArrayAdapter.COST]			= String.valueOf(f.getCost());
	            feedType[ViewUsableItemArrayAdapter.DESCRIPTION]	= f.getDescription();
//	            feedType[ViewUsableItemArrayAdapter.LOCATION]		= f.getStorageLocation()!=null?String.valueOf(location=f.getStorageLocation().getID()):"";
	            feedType[ViewUsableItemArrayAdapter.NAME]			= f.getName();
//	            feedType[ViewUsableItemArrayAdapter.ORIGIN] 		= f.getOrigin()!=null?String.valueOf(owner=f.getOrigin().getID()):"";
//	            feedType[ViewUsableItemArrayAdapter.PURCHASEDATE] 	= f.getPurchaseDate()!=null?String.valueOf(f.getPurchaseDate().getTime()):"";
	            feedType[ViewUsableItemArrayAdapter.QUANTITY] 		= String.valueOf(f.getQuantity());
	            feedType[ViewUsableItemArrayAdapter.QTYMEASUREMENT]	= f.getMeasurement();
//	            feedType[ViewUsableItemArrayAdapter.USED]			= String.valueOf(f.getAmountUsed());
	            
    			feedView = new ViewFeedArrayAdapter(this, feedType);
		    	setPage();
	            
				currentState.putInt(STATEID,FEEDVIEW);
				built=true;
    		}
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Show the menu for an Owner Object
        getMenuInflater().inflate(R.menu.join_menu, menu);
        this.menu=menu;
        return true;
    }

    
    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState (outState);
    	
    	outState.putParcelable("feedView", new StringArrayParcelable().setStrings(feedView.get()));
    	
    	outState.putLong("location", location);
    	outState.putLong("owner", owner);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	feedView = new ViewFeedArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("feedView")).getStrings()[0]);

    	location = inState.getLong("location");
    	owner = inState.getLong("owner");
    	
    	super.onRestoreInstanceState (inState);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	return false;
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_save:
        		if(feedView.isValid()){
	        		edit = false;
	        		
	        		Feed f = id==-1?new Feed():(Feed)LivestockSolutions.getUsableItemByID(id);

//	        		f.setCVDNumber(feedView.get()[0][ViewFeedArrayAdapter.CVDNO]);
//	        		f.setCost(Double.parseDouble(feedView.get()[0][ViewUsableItemArrayAdapter.COST]));
	        		f.setDescription(feedView.get()[0][ViewUsableItemArrayAdapter.DESCRIPTION]);
//	        		f.setStorageLocation(LivestockSolutions.getLocationByID(Long.parseLong(feedView.get()[0][ViewUsableItemArrayAdapter.LOCATION])));
	        		f.setName(feedView.get()[0][ViewUsableItemArrayAdapter.NAME]);
//	        		f.setOrigin((Business)LivestockSolutions.getOwnerByID(Long.parseLong(feedView.get()[0][ViewUsableItemArrayAdapter.ORIGIN])));
//	        		f.setPurchaseDate(new Date(Long.parseLong(feedView.get()[0][ViewUsableItemArrayAdapter.PURCHASEDATE])));
	        		f.setQuantity(Double.parseDouble(feedView.get()[0][ViewUsableItemArrayAdapter.QUANTITY]));
	        		f.setMeasurement(feedView.get()[0][ViewUsableItemArrayAdapter.QTYMEASUREMENT]);
	        		
	        		id=f.getID();
	        		if(LivestockSolutions.addUsableItem(f)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.feed)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.feed),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,FEEDVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		// Pop edit change
	        		stack.pop();
	        		break;
        		}
		        //$FALL-THROUGH$
			default:
	        	return super.frameSelection(frame);
        }
        return true;
    }
    
    
	@Override
	public boolean constructFrame(int view) {
		switch (view) {
			case FEEDVIEW:
				setContentView(RESOURCEID[FEEDVIEW]);
				setPage();
				break;
			default:
				return false;
		}
		return true;
	}
    
    /**
     * Set up the view to show the relevant content
     */
    protected void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	// Not Implemented for a Feed
    	if(edit){
		//	joinView.setModifyFeed();
	    }else{
	    //	joinView.setViewFeed();
	    }
    	feedView.setRoot(itemView);
    	
    	if(itemView != null){
	    	// Get a list of possible Locations.
			Location[] locations = LivestockSolutions.getLocations();
			String[][] locationList = new String[locations.length][];
			
			for(int x=0; x<locations.length; x++){
				String[] item = new String[2];
				item[ViewCattleArrayAdapter.ID]=String.valueOf(locations[x].getID());
				item[ViewCattleArrayAdapter.NAME]=locations[x].getName();
				locationList[x]=item;
			}
			feedView.setLocationList(locationList);
			
			// Get a list of possible Businesses
			Business[] businesses = LivestockSolutions.getOnlyBusinesses();
			String[][] businessList = new String[locations.length][];
			
			for(int x=0; x<businesses.length; x++){
				String[] item = new String[2];
				item[ViewCattleArrayAdapter.ID]=String.valueOf(businesses[x].getID());
				item[ViewCattleArrayAdapter.NAME]=businesses[x].getName();
				businessList[x]=item;
			}
			feedView.setOwnerList(businessList);
			
			View v = feedView.getView(0,null, itemView);
			if(edit || id==-1){
				
			}else{
				View d = v.findViewById(R.id.usableItemLocationList);
				d.setEnabled(location>0);
				if(location>0){
		    		d.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent intent;
							if(LivestockSolutions.getLocationByID(location) instanceof Paddock){
								intent = new Intent(FeedActivity.this, PaddockActivity.class);
							}else{
								intent = new Intent(FeedActivity.this, LocationActivity.class);
							}
							intent.putExtra(ITEMID, location);
					    	startActivityForResult(intent, EXISTING);
						}
					});
				}
				
				d = v.findViewById(R.id.usableItemOriginList);
				d.setEnabled(owner>0);
				if(owner>0){
		    		d.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							Intent intent = new Intent(FeedActivity.this, OwnerActivity.class);
							intent.putExtra(ITEMID, owner);
					    	startActivityForResult(intent, EXISTING);
						}
					});
				}
			}
			itemView.addView(v,0);
    	}
    }
}
